package com.zst.demo1.controller;

import com.zsr.entities.CommonResult;
import com.zsr.entities.RoleDTO;
import com.zsr.entities.UserDTO;
import com.zst.demo1.po.UserRolePO;
import com.zst.demo1.service.Demo2FeignService;
import com.zst.demo1.service.Demo3FeignService;
import com.zst.demo1.service.IUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;

@RestController
@RequestMapping("/zst/demo1")
@Slf4j
public class IndexController {
    @Resource
    private Demo2FeignService demo2FeignService;
    @Resource
    private Demo3FeignService demo3FeignService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @GetMapping("/index")
    public String index() {
        log.info("this is demo1 application.");
        return "this is demo1 application.";
    }

    @GetMapping("/get-user-info/{id}")
    public CommonResult<UserDTO> getUserInfo(@PathVariable("id") Long id) {
        // 调用用户相关信息
        CommonResult<UserDTO> userBase = demo2FeignService.getUserBase(id);
        if (Objects.nonNull(userBase.getData())) {
            log.info(userBase.getData().toString());
        }
        return userBase;
    }

    /**
     * 获取role下的用户信息
     *
     * @param roleId
     * @return
     */
    @GetMapping("/get-user-by-role/{roleId}")
    public CommonResult<UserDTO> getUserByRoleId(@PathVariable("roleId") Long roleId) {
        // 获取角色信息
        CommonResult<RoleDTO> roleDTORes = demo3FeignService.getRole(roleId);
        if (Objects.isNull(roleDTORes.getData()) || Objects.isNull(roleDTORes.getData().getId())) {
            return CommonResult.ResultSuccess(null);
        }
        // 根据角色Id获取用户Id
        Optional<UserRolePO> userRolePOOpt = iUserRoleService.getUserRoleById(roleDTORes.getData().getId());
        if (!userRolePOOpt.isPresent() || Objects.isNull(userRolePOOpt.get().getUserId())) {
            return CommonResult.ResultSuccess(null);
        }
        // 调用用户相关信息
        CommonResult<UserDTO> userBase = demo2FeignService.getOnlyUser(userRolePOOpt.get().getUserId());
        if (Objects.nonNull(userBase.getData())) {
            userBase.getData().setRoleList(Collections.singletonList(roleDTORes.getData()));
        }
        return userBase;
    }
}
